<?php

namespace App\Models;

use App\Models\Traits\HasStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable, SoftDeletes, HasStatus;

    protected $fillable = [
        'username',
        'nickname',
        'email',
        'phone',
        'avatar',
        'password',
        'status',
        'max_devices',
        'dept_id',
        'remark',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'status' => 'integer',
        'max_devices' => 'integer',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles');
    }

    public function department()
    {
        return $this->belongsTo(Department::class, 'dept_id');
    }

    public function hasRole($role)
    {
        if (is_string($role)) {
            return $this->roles()->where('code', $role)->exists();
        }
        return $this->roles()->where('id', $role)->exists();
    }

    public function hasPermission($permission)
    {
        // 管理员拥有所有权限
        if ($this->isAdmin()) {
            return true;
        }

        return $this->roles()->whereHas('permissions', function ($query) use ($permission) {
            $query->where('code', $permission);
        })->exists();
    }

    /**
     * 检查是否有菜单权限
     *
     * @param int|string $menuId 菜单ID或路径
     * @return bool
     */
    public function hasMenuPermission($menuId): bool
    {
        $permissionService = app(\App\Services\PermissionService::class);
        return $permissionService->hasMenuPermission($this, $menuId);
    }

    /**
     * 检查是否有按钮权限
     *
     * @param string $resource 资源标识
     * @param string $action 操作类型
     * @return bool
     */
    public function hasButtonPermission(string $resource, string $action): bool
    {
        $permissionService = app(\App\Services\PermissionService::class);
        return $permissionService->hasButtonPermission($this, $resource, $action);
    }

    /**
     * 检查是否有数据权限
     *
     * @param string $resource 资源标识
     * @param string $action 操作类型
     * @param mixed $dataId 数据ID（可选）
     * @return bool
     */
    public function hasDataPermission(string $resource, string $action, $dataId = null): bool
    {
        $permissionService = app(\App\Services\PermissionService::class);
        return $permissionService->hasDataPermission($this, $resource, $action, $dataId);
    }

    /**
     * 获取用户所有权限
     *
     * @return array
     */
    public function getAllPermissions(): array
    {
        $permissionService = app(\App\Services\PermissionService::class);
        return $permissionService->getUserPermissions($this);
    }

    /**
     * 获取用户按钮权限（按资源分组）
     *
     * @return array
     */
    public function getButtonPermissions(): array
    {
        $permissionService = app(\App\Services\PermissionService::class);
        return $permissionService->getUserButtonPermissions($this);
    }

    public function isAdmin()
    {
        return $this->hasRole('admin');
    }
}

